import os
import shutil
from pathlib import Path
from tempfile import NamedTemporaryFile
from fastapi import APIRouter, Depends, File, UploadFile
from conf.settings import base_dir, download_url
from utils.result_back import success, fail
from fastapi_jwt_auth import AuthJWT

router = APIRouter()


@router.post("/image", summary="上传图片")
async def upload_image(file: UploadFile = File(...), Authorize: AuthJWT = Depends()):
    Authorize.jwt_required()
    # 本地存储临时方案，一般生产都是使用第三方云存储OSS(如七牛云, 阿里云)
    save_dir = f"{base_dir}/assets"
    if not os.path.exists(save_dir):
        os.mkdir(save_dir)
    try:
        suffix = Path(file.filename).suffix

        with NamedTemporaryFile(delete=False, suffix=suffix, dir=save_dir) as tmp:
            shutil.copyfileobj(file.file, tmp)
            tmp_file_name = Path(tmp.name).name
    finally:
        file.file.close()

    return success({"url": f"{download_url}/assets/{tmp_file_name}", "filename": tmp_file_name})
